package com.design.interpreter;

import java.util.Stack;

/**
 * @author leali
 * @title: InstructionHandler
 * @projectName design
 * @description: 指令处理类：工具类
 * @date 2022/1/3 18:21
 */
public class InstructionHandler {
    private AbstractNode node;

    public void handle(String instruction) {
        AbstractNode left, right;
        AbstractNode direction, action, distance;
        //声明一个栈对象用于存储抽象语法树
        Stack stack = new Stack();
        //以空格分隔指令字符串
        String[] words = instruction.split(" ");
        for (int i = 0; i < words.length; i++) {
            //本实例采用栈的方式来处理指令，如果遇到“and”，则将其后的三个单词作为三个终结符表达式连成一个简单句子SentenceNode作为“and”的右表达式，
            // 而将从栈顶弹出的表达式作为“and”的左表达式，最后将新的“and”表达式压入栈中。
            if ("and".equalsIgnoreCase(words[i])) {
                //弹出栈顶表达式作为左表达式
                left = (AbstractNode) stack.pop();
                // 表达式顺序方向+动作+距离 eg:up move 5
                direction = new DirectionNode(words[++i]);
                action = new ActionNode(words[++i]);
                distance = new DistanceNode(words[++i]);
                //右表达式
                right = new SentenceNode(direction, action, distance);
                //将新表达式压入栈中
                stack.push(new AndNode(left, right));
            }
            //如果是从头开始进行解释，则将前三个单词组成一个简单句子SentenceNode并将该句子压入栈中
            else {
                direction = new DirectionNode(words[i]);
                action = new ActionNode(words[++i]);
                distance = new DistanceNode(words[++i]);
                left = new SentenceNode(direction, action, distance);
                //将新表达式压入栈中
                stack.push(left);
            }
        }
        //将全部表达式从栈中弹出
        this.node = (AbstractNode) stack.pop();
    }

    public String output() {
        return node.interpret();
    }
}
